package com.jtpay.sdk.jtpay.utils;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.text.TextUtils;

import java.io.File;

public class PayInstallUtil {

    protected Context mContext;

    public PayInstallUtil(Context context) {
        mContext = context;
    }

    public void installApk(String path) throws NullPointerException {
        PayLogUtil.log("installApk path = " + path);

        if (TextUtils.isEmpty(path))
            throw new NullPointerException("install apk path cannot empty");

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        File file = new File(path);
        intent.setDataAndType(Uri.parse("file://" + file), "application/vnd.android.package-archive");
        mContext.startActivity(intent);
    }

    public void unInstallApk(String packageName) throws NullPointerException {
        PayLogUtil.log("unInstallApk packagename = " + packageName);

        if (TextUtils.isEmpty(packageName))
            throw new NullPointerException("uninstall apk package name cannot empty");

        Uri packageURI = Uri.parse("package:" + packageName);
        Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
        mContext.startActivity(uninstallIntent);
    }

    public boolean checkApkExist(String packageName) {
        PayLogUtil.log("checkApkExist packagename = " + packageName);

        if (TextUtils.isEmpty(packageName))
            return false;

        try {
            mContext.getPackageManager()
                    .getApplicationInfo(packageName,
                            PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

}
